import com.mit.web.business.proxy.MaintenanceProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.util.FlexUtil;
import com.mit.web.util.LogUtil;
import com.mit.web.util.Validator;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.vo.maintenance.ProductColorVO;

import flash.events.MouseEvent;

import mx.collections.ArrayCollection;
import mx.controls.DataGrid;
import mx.controls.TextInput;
import mx.events.DataGridEvent;
import mx.events.DataGridEventReason;
import mx.logging.ILogger;
import mx.resources.ResourceManager;
import mx.rpc.events.ResultEvent;
import mx.utils.StringUtil;


private var _maintenanceProxy:MaintenanceProxy = MaintenanceProxy.getInstance();
[Bindable] private var _colorList:ArrayCollection = new ArrayCollection();
private var _orgColorLst:ArrayCollection = new ArrayCollection();
private var _logger:ILogger;
private var _pm:IProgressMonitor;

private function init():void{
	_logger = LogUtil.getLogger(this);
	doRetrieve();
}

private function doRetrieve():void{
	var responder:IInvokeResponder = _maintenanceProxy.getProductColors().installProgressBar(_pm, this);	
	responder.addResultListener(retrieveListHandler);
	responder.addFaultListener(exceptionHandler);
}

private function retrieveListHandler(event:ResultEvent):void{
	_colorList = event.result as ArrayCollection;
	_logger.debug("_colorList: " + _colorList);
	for each(var o:Object in _colorList){
		o.saveOriginal();
	}
	grd_color.validateNow();
}

private function doNew(event:MouseEvent):void{
	_colorList.addItem(new ProductColorVO()); 
	grd_color.validateNow();
	grd_color.editedItemPosition = {columnIndex:0, rowIndex:_colorList.length - 1};
}

private function doSave(event:MouseEvent):void{
	//Auto remove newly created empty record
	var cloneList:ArrayCollection = new ArrayCollection();
	cloneList = FlexUtil.deepClone(_colorList) as ArrayCollection;
	for each (var color:Object in cloneList) {
		if (color.id < 1 && (color.name == null || color.name == "") && (color.code == null || color.code == "")) {
			_colorList.removeItemAt(_colorList.getItemIndex(color));
		}	
	}
	grd_color.validateNow();
	
	//validation to privent duplicate record
	//Why not validate when users focus out? because it will prevent users switching the name or  the code.
  	if (!validate()) {
 	 	event.preventDefault();
  		return;
  	}
	
	// Update List
	var paramList:ArrayCollection = new ArrayCollection();
	for each (var color:Object in _colorList) {
		/*_logger.debug("color: color.code=" + color.code + ", color.name=" + color.name
			+ ", color.selectedColor=" + color.selectedColor);   */
		if (color.original == null) {
			// new color
			_logger.debug("create color: code=" + color.code + ", name=" + color.name
				+ ", color=" + color.color);
			paramList.addItem(color);
		} else {
			// update color
			if (color.name != color.original.name 
					|| color.code != color.original.code
					|| color.color != color.original.color) {
				paramList.addItem(color);
			} else {
				_logger.debug("color: code=" + color.code 
					+ ", name=" + color.name 
					+ ", color=" + color.color
					+ " is not changed");
			}
		}
	}
	
	//Save
 	if (paramList.length > 0) {
		var responder:IInvokeResponder = _maintenanceProxy.updateProductColors(
			paramList).installProgressBar(_pm, this);
		responder.addResultListener(savedHandler);
		responder.addFaultListener(exceptionHandler);
	}
}

private function savedHandler(event:ResultEvent):void {
	retrieveListHandler(event);
	showMessageTip(ResourceManager.getInstance().getString(
		Constants.BUNDLE_COMMON,"info.common.saveOk"),  grd_color);
}

private function validate():Boolean{
	var colorCloneList:ArrayCollection = new ArrayCollection();
	colorCloneList= FlexUtil.deepClone(_colorList) as ArrayCollection;
	for each(var color:Object in _colorList){
		var name:String = color.name;
		var code:String = color.code;
		
		var hasError:Boolean = false;
		var myError:String;
		
		if (name == null || name == "") {
			myError = ResourceManager.getInstance().getString(
				Constants.BUNDLE_COMMON,"error.common.requiredField");
			grd_color.editedItemPosition = {columnIndex:1, rowIndex:_colorList.getItemIndex(color)};
			hasError = true;
		} else if (code == null || code == "" ) {
			myError = ResourceManager.getInstance().getString(
				Constants.BUNDLE_COMMON,"error.common.requiredField");
			grd_color.editedItemPosition = {columnIndex:0, rowIndex:_colorList.getItemIndex(color)};
			hasError = true;
		}
		
		if (!hasError) {
			for each (var colorClone:Object in colorCloneList) {
				//Error found! both are new item, how to handle?!
				if (name == colorClone.name && colorCloneList.getItemIndex(colorClone) 
						!= _colorList.getItemIndex(color)) {
					//duplicate name
					myError = ResourceManager.getInstance().getString(
						Constants.BUNDLE_COMMON,"error.common.duplicateKey",[name]);
					grd_color.editedItemPosition = {columnIndex:1, rowIndex:_colorList.getItemIndex(color)};
					hasError = true;
					break;
				} else if (code == colorClone.code && colorCloneList.getItemIndex(colorClone) 
						!= _colorList.getItemIndex(color)){
					//duplicate code
					myError = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.duplicateKey",[code]);
					grd_color.editedItemPosition = {columnIndex:0, rowIndex:_colorList.getItemIndex(color)};
					hasError = true;
					break;
				}
			}
		}
		
		if (hasError) {
			showVerticalMiddleErrorTipAt(myError, grd_color);
			return false;
		}
	}
	return true;
}

/*
protected function dg_itemEditEndHandler(event:DataGridEvent):void {
	//如果用户点击escape或者其他地方，取消输入
	if (event.reason == DataGridEventReason.CANCELLED) {
		return;		
	} 

	_logger.debug("event.columnIndex=" + event.columnIndex + ", event.rowIndex=" + event.rowIndex);
	
	// Get the name of the column being editted.
	var colName:String = grd_color.columns[event.columnIndex].dataField;
	_logger.debug("colName: " + colName);
	if (colName == "color") {
		_logger.debug("COLOR!!!");
		_logger.debug("grd_color.editedItemRenderer.data: " + grd_color.editedItemRenderer.data);
		_logger.debug("color: " + grd_color.editedItemRenderer.data.color);;
	}
}  */

// Obsoleted code, will be used to for study later
/*
protected function grd_color_itemEditEndHandler(event:DataGridEvent):void
{
	//如果用户点击escape或者其他地方，取消输入
	if( event.reason == DataGridEventReason.CANCELLED ) return;
	
	//只验证名称和色码
	if( event.dataField == "name" || event.dataField == "code"){
		var txt:TextInput = (event.currentTarget as DataGrid).itemEditorInstance as TextInput;
		//Trim input
		txt.text = StringUtil.trim(txt.text);
		//必须输入
		if(Validator.isNullOrBlank(txt.text)){
			//取消事件
			
			txt.errorString= ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.requiredField");		
			event.preventDefault();
			return;
		}
		var rowIndex : int = event.rowIndex;
		var columnIndex:int =  event.columnIndex ;
		if(event.dataField == "name"){
			for(var i:int = 0; i<_colorList.length;i++){
				
				if(txt.text == _colorList[i].name && rowIndex != i){
					
					txt.errorString= ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.duplicateKey",[txt.text]);		
					event.preventDefault();
					return;
				}
			}
		}
		if(event.dataField == "code"){
			for(var j:int = 0; j<_colorList.length;j++){

				if(txt.text  == _colorList[j].code && rowIndex != j){
					
					txt.errorString= ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.duplicateKey",[txt.text]);		
					event.preventDefault();
					return;
				}
			}
		}
	}

}
*/

